from Crypto.Cipher import DES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes

""" 
ECB模式 电子密码本模式
"""

def encrypt(message, key):
    cipher = DES.new(key, DES.MODE_ECB)
    ct_bytes = cipher.encrypt(pad(message.encode("utf-8"), DES.block_size))
    return ct_bytes.hex()


def decrypt(encrypted_hex, key):
    cipher = DES.new(key, DES.MODE_ECB)
    ct = bytes.fromhex(encrypted_hex)
    pt = unpad(cipher.decrypt(ct), DES.block_size)
    return pt.decode("utf-8")


# 示例
key = get_random_bytes(8)  # DES密钥长度为8字节
message = "hello world"

# 加密
cipher_text = encrypt(message, key)
print("Encrypted:", cipher_text)

# 解密
plain_text = decrypt(cipher_text, key)
print("Decrypted:", plain_text)
